const Koa = require("koa");
const koaBody = require("koa-body");
const app = (module.exports = new Koa());
const views = require("koa-views");
const logger = require("koa-logger");

const routers = require("./router/index");

// 在使用之前设置好模板引擎
app.use(
  views(__dirname + "/views", {
    extension: "ejs",
  })
);

// 添加日志
app.use(logger());

app.use(koaBody());

app.use(async function (ctx, next) {
  // if (!ctx.req.headers || typeof ctx.req.headers !== "object") {
  //   throw new TypeError("argument req is required to have headers property");
  // }

  await next();
  return;

  // let _white_url = ["/api/login", "/api/freshtoken", "/api/tokenlogin"];
  // let _header_token = ctx.req.headers.token;
  // let _cookie_token = ctx.cookies.get("token");

  // if (
  //   _white_url.includes(ctx.path) ||
  //   // (_header_token && _header_token == routers.getUniqueId())
  //   (_cookie_token && _cookie_token == routers.getUniqueId())
  // ) {
  //   await next();
  // } else {
  //   ctx.throw(401);
  // }
});

app.use(routers.routers.routes());

if (!module.parent) app.listen(3001);
